/*
 * @Author: xiaosihan
 * @Date: 2023-04-18 15:18:19
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-08-14 21:36:57
 */

import utils from '@utils';
import axios, { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { get } from 'lodash';

// 请求的基类
export default class Api {
  constructor() {}

  //访问域名
  baseURL = '';

  //开发模式访问的域名
  devBaseURL = '/api';

  //超时时间
  timeout = 60000;

  // 带凭据
  withCredentials = false;

  // 创建 请求实例
  _createInstance({ headers = { 'Content-Type': 'application/x-www-form-urlencoded' } }: { headers?: any }) {
    const axioxInstance = axios.create({
      baseURL: utils.isDev ? this.devBaseURL : this.baseURL,
      timeout: this.timeout,
      headers: {
        ...headers,
      },
      withCredentials: this.withCredentials,
    });

    // 请求拦截器
    axioxInstance.interceptors.request.use(
      (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
        // 部分接口需要拿到Token
        // let token = localStorage.getItem('token');
        // let admin_authorization = localStorage.getItem('admin_authorization');
        // if (token) {
        //     config.headers!.authorization = token;
        // }
        // if (admin_authorization) {
        //     config.headers!.admin_authorization = admin_authorization;
        // }
        config.data = config.data;
        return config;
      },
      (err: any) => {
        return Promise.reject(err);
      }
    );

    // 响应拦截器
    axioxInstance.interceptors.response.use(
      (res: AxiosResponse): AxiosResponse => {
        return res.data.data;
      },
      (err: any) => {
        let code = get(err, ['response', 'data', 'code']);
        if ([401, 402].includes(code)) {
          // localStorage.clear();
          // globalStore.setLoginModal(true);
        } else if ([200].includes(code)) {
        } else {
          return Promise.reject(new Error(get(err, ['response', 'data', 'message'])));
        }
      }
    );

    return axioxInstance;
  }

  // get请求
  _get(url: string, params?: {}) {
    const axioxInstance = this._createInstance({});
    return axioxInstance.get(url, { params });
  }

  // post 请求
  _post(url: string, data = {}) {
    const axioxInstance = this._createInstance({ headers: {} });
    return axioxInstance.post(url, data);
  }

  // 上传
  _upload(url: string, file: any) {
    const axioxInstance = this._createInstance({});
    return axioxInstance.post(url, file);
  }
}
